package com.uuah.server.util.spring;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.uuah.config.i18n.MessageFactory;
import com.uuah.config.object.AbstractObjectFactory;
import com.uuah.exception.lifecycle.InitialisationException;

public class SpringBeanLookup extends AbstractObjectFactory implements
		ApplicationContextAware {
	private ApplicationContext applicationContext;
	private String bean;

	public void initialise() throws InitialisationException {
		if (bean == null) {
			throw new InitialisationException(MessageFactory
					.createStaticMessage("Bean name has not been set."), this);
		}
		if (applicationContext == null) {
			throw new InitialisationException(
					MessageFactory
							.createStaticMessage("ApplicationContext has not been injected."),
					this);
		}
	}

	public void dispose() {
		// Not implemented for Spring Beans
	}

	public Class getObjectClass() {
		return applicationContext.getType(bean);
	}

	public Object getInstance() throws Exception {
		Object instance = applicationContext.getBean(bean);
		fireInitialisationCallbacks(instance);
		return instance;
	}

	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.applicationContext = applicationContext;
	}

	public String getBean() {
		return bean;
	}

	public void setBean(String bean) {
		this.bean = bean;
	}

	// @Override
	public boolean isSingleton() {
		return applicationContext.isSingleton(bean);
	}
}
